﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UCS.ArtificialInteligence.AI
{
    public class AStarList
    {
        private AStarListNode _first;

        public void Add(int value, int depth, IProblemState state)
        {
            AStarListNode adding = new AStarListNode(value, depth, state);

            if (_first == null)
                _first = adding;
            else
            {
                AStarListNode current = _first;
                AStarListNode previous = null;
                bool added = false;

                do
                {
                    if (adding.Value < current.Value)
                    {
                        adding.Next = current;

                        if (previous != null)
                            previous.Next = adding;

                        if (current == _first)
                            _first = adding;

                        added = true;
                    }

                    previous = current;
                    current = current.Next;
                }
                while (current != null && !added);

                if (!added)
                    previous.Next = adding;
            }
        }

        public AStarListNode Remove()
        {
            if (_first == null)
                return null;

            AStarListNode result = _first;

            if (_first.Next == null)
            {
                _first = null;
                return result;
            }

            _first = _first.Next;

            return result;
        }

        public bool ContainsState(IProblemState state)
        {
            var current = _first;

            while (current != null)
            {
                if (current.State.Equals(state))
                    return true;

                current = current.Next;
            }

            return false;
        }
    }
}
